package com.liuweiheng.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 测试Hystrix服务降级访问
 *
 * @author kasuganosora
 * @since 2020/10/11 15:57
 */
@Service
public class PaymentService {


    //=============================================== 服务降级

    /**
     * 正常访问
     */
    public String paymentInfoOk(int id) {
        return "线程池：" + Thread.currentThread().getName() + "paymentInfo_OK, id：" + id;
    }


    /**
     * 超时访问
     */
    @HystrixCommand(
            fallbackMethod = "paymentInfoTimeoutHandler",
            commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="1000")}
    )
    public String paymentInfoTimeout(int id) {
        // 测试服务出现异常现象：
//        int age = 10/0;

        // 测试服务出现超时现象：
        try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); }

        return "线程池：" + Thread.currentThread().getName() + "paymentInfo_Timeout, id：" + id;
    }
    public String paymentInfoTimeoutHandler(int id) {
        return "线程池：" + Thread.currentThread().getName() + "paymentInfo_Timeout_handler, id：" + id + "\t" + "o(╥﹏╥)o";
    }




    //=============================================== 服务熔断


    /**
     * 测试服务熔断
     * HystrixCommandProperties.class --> 查看HystrixProperty中的成员变量
     * @param id (-1:抛出异常 1:正常运行)
     */
    @HystrixCommand(
            fallbackMethod = "paymentCircuitBreakerFallback",
            commandProperties = {
                    // 开启断路器
                    @HystrixProperty(name="circuitBreaker.enabled", value="true"),
                    // 设置时间窗口期
                    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds", value="10000"),
                    // 设置请求次数
                    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold", value="10"),
                    // 设置失败率，规定时间内，请求失败率达到则熔断
                    @HystrixProperty(name="circuitBreaker.errorThresholdPercentage", value="60")
            }
    )
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("抛出运行时异常");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功，流水号：" + serialNumber;
    }

    public String paymentCircuitBreakerFallback(Integer id) {
        return "id不能为负数，请稍后重试，id：" + id;
    }
}
